package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   异步请求创建节点
 *          IStringCallback : 异步请求回调接口
 * @author: cww
 * @DateTime: 2020/1/17 9:49
 */

public class ZooKeeperCreateNodeASyncAPI implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("home:2181", 5000, new ZooKeeperCreateNodeASyncAPI());
        connectedSemaphore.await();

        zooKeeper.create("/zk-test-ephemeral-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL, new IStringCallback(),"I am context");
        // 创建该节点将返回 -110 code 因为上面已经创建过同名 node
        zooKeeper.create("/zk-test-ephemeral-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL, new IStringCallback(),"I am context");
        zooKeeper.create("/zk-test-ephemeral-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL, new IStringCallback(),"I am context");
        Thread.sleep(5000);

    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }
}

class IStringCallback implements AsyncCallback.StringCallback {

    /**
     *
     * @param rc    服务响应码
     *              0:      接口调用成功(ok)
     *              -4:     客户端和服务端连接已断开(ConnectionLoss)
     *              -110:   指定节点已存在(NodeExists)
     *              -112:   会话已过期(SessionExpired)
     * @param path  在调用异步接口时传入 API 的数据节点的节点路径参数值
     * @param ctx   在调用异步接口时传入 API 的 ctx 参数值(实际可以用于传递上下文等)
     * @param name  实际在服务端创建的节点名，适用于创建顺序节点由服务端返回节点路径
     */
    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
        System.out.println("Create path result: [" + rc + "," + path + "," + ctx + ", real path name: " + name);
    }
}
